<template>
	<cl-page :padding="20">
		<view class="page">
			<cl-card :label="id?'编辑货主':'新增货主'">
				<cl-form ref="Form" v-model="form" :rules="rules" :disabled="loading" label-position="left">
					<cl-form-item prop="owner_name">
						<template #label><span class="required-icon">*</span>货主名称</template>
						<cl-input v-model="form.owner_name" placeholder="请填写货主名称" />
					</cl-form-item>
					<cl-form-item v-if="code">
						<template #label><span class="required-icon">*</span>标识码</template>
						{{code}}
					</cl-form-item>
				</cl-form>
			</cl-card>

			<cl-footer border>
				<cl-button size="large" round fill @tap="submit" :loading="loading" background-color="#008c8c"
					color="#fff">
					{{id?"保存":'生成标识码'}}
				</cl-button>
			</cl-footer>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
	import { reactive, ref } from "vue";
	import { useUi } from "/$/cool-ui";
	import { onPageScroll } from "@dcloudio/uni-app";
	import { useCool } from "/@/cool";
	import { onHide } from "@dcloudio/uni-app";
	import { onLoad } from "@dcloudio/uni-app";


	const { storage } = useCool()
	onPageScroll((e) => { });

	const ui = useUi();

	const form = ref({
		owner_name: ""
	});

	const rules = reactive({
		owner_name: {
			required: true,
			message: "货主名称不能为空",
		},
	});

	const Form = ref<ClForm.Ref>();
	const db = uniCloud.importObject('cc_code') //第一步导入云对象
	const loading = ref(false);
	const id = ref<string>("")
	const code = ref<string>("")
	onHide(() => {
		form.value = {
			owner_name: "",
		}
		code.value = ''
		id.value = ''
	})
	const getDetail = async () => {
		const res = await db.detail(id.value)
		form.value = res.data[0] || {}
		code.value = res.data[0].code
	}
	onLoad(async (query : any) => {
		id.value = query.id
		if (id.value) {
			getDetail()
		}

	})
	async function submit() {
		Form.value?.validate(async (valid) => {
			if (valid) {
				loading.value = true;
				if (!id.value) {
					const { data, code: resCode, msg } = await db.add({ ...form.value });
					code.value = data?.code || ''
					if (resCode === 400) {
						ui.showToast(msg);
					} else {
						ui.showToast("创建成功");
					}
				} else {
					await db.edit({ ...form.value, _id: id.value });
					ui.showToast("编辑成功");
				}

				loading.value = false;
			}
		});
	}
</script>
<style scoped>
	.required-icon {
		color: red;
	}
</style>